package com.exam.serviceimpl;

import com.exam.entity.*;
import com.exam.mapper.ExamPaperRepository;
import com.exam.mapper.FillQuestionRepository;
import com.exam.mapper.JudgeQuestionRepository;
import com.exam.mapper.MultiQuestionRepository;
import com.exam.service.ExamPaperService;
import com.exam.service.QuestionRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ExamPaperServiceImpl implements ExamPaperService {

    @Autowired
    private QuestionRuleService questionRuleService;

    @Autowired
    private FillQuestionRepository fillQuestionRepository;

    @Autowired
    private MultiQuestionRepository multiQuestionRepository;

    @Autowired
    private JudgeQuestionRepository judgeQuestionRepository;

    @Autowired
    private ExamPaperRepository examPaperRepository;

    @Override
    public ExamPaper generateExamPaper(Long ruleId) {
        QuestionRule rule = questionRuleService.getQuestionRuleById(ruleId);
        if (rule == null) {
            throw new IllegalArgumentException("QuestionRule not found!");
        }

        // 获取题目
        List<FillQuestion> fillQuestions = fillQuestionRepository.findAll().stream()
                .filter(q -> q.getSubject().equals(rule.getSubject()))
                .limit(rule.getFillQuestionCount())
                .collect(Collectors.toList());

        List<MultiQuestion> multiQuestions = multiQuestionRepository.findAll().stream()
                .filter(q -> q.getSubject().equals(rule.getSubject()))
                .limit(rule.getMultiQuestionCount())
                .collect(Collectors.toList());

        List<JudgeQuestion> judgeQuestions = judgeQuestionRepository.findAll().stream()
                .filter(q -> q.getSubject().equals(rule.getSubject()))
                .limit(rule.getJudgeQuestionCount())
                .collect(Collectors.toList());

        // 创建试卷
        ExamPaper examPaper = new ExamPaper();
        examPaper.setName("Generated Exam Paper");
        examPaper.setSubject(rule.getSubject());
        examPaper.setTotalQuestions(fillQuestions.size() + multiQuestions.size() + judgeQuestions.size());
        examPaper.setTotalScore(100); // 假设固定 100 分

        List<String> questionIds = new ArrayList<>();
        fillQuestions.forEach(q -> questionIds.add("F-" + q.getId()));
        multiQuestions.forEach(q -> questionIds.add("M-" + q.getId()));
        judgeQuestions.forEach(q -> questionIds.add("J-" + q.getId()));
        examPaper.setQuestions(questionIds);

        return examPaperRepository.save(examPaper);
    }

    @Override
    public ExamPaper getExamPaperById(Long id) {
        return examPaperRepository.findById(id).orElse(null);
    }
}